<?php

namespace app\http\middleware;

use app\facade\Token;
use app\models\{User as Users, UserConfig};
use think\Db;
use app\facade\Redis;

class Auth
{
    use \traits\controller\Jump;
    public function handle($request, \Closure $next)
    {
        $url = '/' . $request->controller() . '/' . $request->action();
        $verify = config('auth.api');
        $url = strtolower($url);
        if (!in_array($url, $verify) && !$request->header('token')) {
            $this->result([], 999, 'token不能为空');
        }
        $code = $request->ip();
        if ($request->header('token') && !in_array($url, $verify)) {
            $user_id = Token::get($request->header('token'));
            $user = Users::where('id', $user_id)->find();
            $code = $user_id;
            if (!$user) {
                $this->result([], 998, '账号不存在');
            }
            if ($user['status'] == 2) {
                $this->result([], 997, '账号已被冻结');
            }
            if ($request->header('token') != $user['token']) {
                $this->result([], 996, '账号已在别处登录');
            }
            $level = (new UserConfig())->order('level desc')->where('pnumber', '<=', $user['tmoney'])->value('level') ?? 0;
            if ($level >= 1 && $user['level'] != $level && $user['level'] > 0) {
                Users::where('id', $user_id)->update(['level' => $level]);
                $user['level'] = $level;
            }
            $request->user_id = $user_id;
            $request->user = $user;
        }
        if ($request->isPost() && $url != '/other/oss') {
            $unique = $url . '_' . $code;
            $frtimes = Redis::get($unique);
            if ($frtimes) {
                $this->result([], 10000, '请求频繁，请2秒后重试');
            }
            Redis::setex($unique, 2, 2);
        }
        return $next($request);
    }
}
